//
//  ATPhotoTool.m
//  AT
//
//  Created by CoderLT on 15/3/23.
//  Copyright (c) 2015年 Summer. All rights reserved.
//

#import "ATPhotoTool.h"
#import <CTAssetsPickerController/CTAssetsPickerController.h>

@interface ATPhotoTool () <CTAssetsPickerControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, copy) void(^completion)(id object);
@end

@implementation ATPhotoTool
static ATPhotoTool *_instance;
+ (instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    return _instance;
}

+ (void)pickerVideo:(void (^)(AVAsset *))completion {
    CTAssetsPickerController * picker = [[CTAssetsPickerController alloc] init];
    picker.delegate = [ATPhotoTool sharedInstance];
    PHFetchOptions *fetchOptions = [PHFetchOptions new];
    fetchOptions.predicate = [NSPredicate predicateWithFormat:@"mediaType == %d", PHAssetMediaTypeVideo];
    picker.assetsFetchOptions = fetchOptions;
    picker.showsEmptyAlbums = NO;
    picker.alwaysEnableDoneButton = NO;
    picker.defaultAssetCollection = PHAssetCollectionSubtypeSmartAlbumUserLibrary;
    [[UIViewController rootTopPresentedController] presentViewController:picker animated:YES completion:nil];
    
    [ATPhotoTool sharedInstance].completion = ^(NSArray<PHAsset *> *assets) {
        [assets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
            PHVideoRequestOptions *option = [PHVideoRequestOptions new];
            [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:option resultHandler:^(AVAsset * avasset, AVAudioMix * audioMix, NSDictionary * info) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    AVURLAsset *result = ((AVURLAsset *)avasset);
                    NSURL *pathURL = result.URL;
                    if ([pathURL.pathExtension.lowercaseString isEqualToString:@"3gp"]) {
                        [MBProgressHUD showMessage:@"视频格式不支持"];
                        result = nil;
                    }
                    !completion ?: completion(result);
                });
            }];
            *stop = YES;
        }];
    };
}

+ (void)pickerPhoto:(BOOL)allowsEditing completion:(void (^)(UIImage *))completion {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.allowsEditing = allowsEditing;
    picker.delegate = [ATPhotoTool sharedInstance];
    [[UIViewController rootTopPresentedController] presentViewController:picker animated:YES completion:nil];
    
    [ATPhotoTool sharedInstance].completion = ^(UIImage *image) {
        !completion ?: completion(image);
    };
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = nil;
    if (picker.allowsEditing) {
        image = [info objectForKey:UIImagePickerControllerEditedImage];
    }
    else{
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    !self.completion ?: self.completion(image);
    self.completion = nil;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    !self.completion ?: self.completion(nil);
    self.completion = nil;
}

#pragma mark - CTAssetsPickerControllerDelegate
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(PHAsset *)asset {
    [picker.selectedAssets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [picker deselectAsset:obj];
    }];
    return YES;
}
- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldEnableAsset:(PHAsset *)asset {
    if (asset.mediaType == PHAssetMediaTypeVideo) {
        return asset.duration >= 10.0f;
    }
    return YES;
}

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets {
    [picker dismissViewControllerAnimated:YES completion:nil];
    !self.completion ?: self.completion(assets);
    self.completion = nil;
}

- (void)assetsPickerControllerDidCancel:(CTAssetsPickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
    !self.completion ?: self.completion(nil);
    self.completion = nil;
}

@end
